package client

import (
	"fmt"
	"gopkg.in/ini.v1"
	"log"
)

const (
	//configPath = "nasgui.ini"
	configPath = "/nasgui/storage/config/nasgui.ini"
)

var SPNode *SPNodes = new(SPNodes)

type SPNodes struct {
	Nodes  map[string]string
	Passwd map[string]string
	Hosts  map[string]string
}

func init() {
	var err error
	SPNode.Nodes, err = GetIniConfig("ip")
	if err != nil {
		log.Fatal(err)
	}
	SPNode.Passwd, err = GetIniConfig("passwd")
	if err != nil {
		log.Fatal(err)
	}
	SPNode.Hosts, err = GetIniConfig("agent")
	if err != nil {
		log.Fatal(err)
	}
}

// GetIniConfig 获取配置字段列表并转化为SP  node0_ip -> SP1
func GetIniConfig(str string) (map[string]string, error) {
	cfg, err := ini.Load(configPath)
	if err != nil {
		return nil, err
	}
	newMap := make(map[string]string)
	hash := cfg.Section(str).KeysHash()
	list := cfg.Section(str).KeyStrings()
	if len(list) == 0 || hash == nil {
		return nil, fmt.Errorf("%s No %s field", configPath, str)
	}
	for i, k := range list {
		newKey := fmt.Sprintf("L:SP%d", i+1)
		newMap[newKey] = hash[k]
	}
	return newMap, nil
}
